package com.ks.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @作者 yan
 * @创建日期 2017-3-21 9:43:23
 * @版本 V1.0
 * @描述
 */
public class JwtUtil {

    private static final int EXPIRATION = 60; // 失效时间为1分钟
    private static final String SIGN_KEY = "CRRC_SF_EAM_APP";
    private static final String SUBJECT = "HNGS";

    /**
     * 获取Token信息
     *
     * @param swry_dm
     * @param sfzh
     * @param sjhm
     * @param imei
     * @param imsi
     * @return
     */
    public static String getToken(final String user_dm) {
        return Jwts.builder().setSubject(SUBJECT).claim("swry_dm", user_dm).setIssuedAt(new Date())
                .setExpiration(DateUtil.afterAddingSomeMins(EXPIRATION))// 设置失效时间
                .signWith(SignatureAlgorithm.HS256, SIGN_KEY).compact();
    }

    /**
     * 解析Token
     *
     * @param swry_dm
     * @param sfzh
     * @param imei
     * @param imsi
     * @param token
     * @return
     */
    public static Map<String, Object> parseToken(final String token, final String user_dm) {
        Map<String, Object> map = new HashMap<>();

        int no = -1;
        String msg = "非法访问";

        try {
            // 解析客户端传递过来的TOKEN信息
            final Claims claims = Jwts.parser().setSigningKey(SIGN_KEY).parseClaimsJws(token).getBody();

            // 进行权限验证
            boolean isValidSwry_dm = claims.get("swry_dm").equals(user_dm);

            if (isValidSwry_dm) {
                no = 1;
                msg = "验证通过";
            }
        } catch (SignatureException e) {
            msg = "TOKEN信息本地不存在，请重新登录。";
        } catch (ExpiredJwtException e) {
            no = 1;
            msg = "验证通过";
        } catch (Exception e) {
            no = -2;
            msg = "非法访问，请重新注册";
        }

        map.put("no", no);
        map.put("msg", msg);

        return map;
    }

    public static void main(String[] args) {
        String ss = getToken("1");
        System.out.println(ss);
    }
}
